import socket, sys

arguments = sys.argv

badmode = arguments[1] == 'bad'
address = '0.0.0.0'
port = int(arguments[2])
simultaneous_clients=5

data_length = 64

print 'address:' , address
print 'port:' , port
print 'clients:' , simultaneous_clients

username = 'manager' if badmode else 'notdefault'
password = 'friend' if badmode else 'notdefault'
print 'username:', username
print 'password:', password

request_msg = ['OFS1 login:','Password:','Last login:','Login incorrect','Connection closed by foreign host.']
state = 0
enabled = True
tries_count = 0

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (address,port)

sock.bind(server_address)

sock.listen(simultaneous_clients)

while enabled:
    print 'Waiting for brute socket connection...'
    connection, client_address = sock.accept()
    try:
        connection.sendall(request_msg[0])

        while True:
            data = connection.recv(data_length)
            print 'recv %d: %s\n' % (state, data.strip())
            if data:
                if state == 0:
                    user = data
                    connection.sendall(request_msg[1])
                    state = 1
                elif state == 1:
                    salt = data
                    if username == user and password == salt:
                        connection.sendall(request_msg[2])
                        state = 2
                    else:
                        if tries_count == 2:
                            connection.sendall(request_msg[4])
                            break
                        else:
                            connection.sendall(request_msg[3])
                            tries_count = tries_count + 1
                            connection.sendall(request_msg[0])
                            state = 0
            else:
                state = 0
                break
    except Exception as e:
        print 'Exception: ', e
    finally:
        print 'Done with connection.'
        connection.close()
